import classNames from "classnames"
import { useAppSelector } from "../../../../utils/storeHook/storeHook"
import { memo, useState } from "react"
import './index.scss'
import {SettingFilled, SettingOutlined,SearchOutlined,} from '@ant-design/icons';
import { message } from "antd";
import { MyInput, MyButton, MyDialog, MyCheckBox,ConfirmDialog } from "../../../../components";
import http from "../../../../utils/http";
import api from "../../../../api";

interface ChannelItemT {
    channel_id:string,
    name:string,
    position:number,
    server_id:string,
    type:string,
    created_at:string,
}

interface propsT{
    channelItem:ChannelItemT,
    onClick:Function,
    disabled?:boolean,
    role?:string,
    reNewChannelList:Function
}

interface ChannelSettingT{
    channel_id:string,
    name:string,
    position:number,
    server_id:string,
    type:string,
    created_at:string,
    descripe:string,
    channel_count:number
}

interface memberT{
    user_id:string,
    member_id:string,
    username:string,
    avatarUrl:string,
    userType:string,
    channel_id:string,
    channelType:string,
    role:string,
    can_view:boolean,
    can_send:boolean,
    can_manage:boolean,
    can_connect:boolean,
    is_muted:boolean,
}

const MemberPermissionCard = memo(({memberItem,permitChange}:{memberItem:memberT,permitChange:Function})=>{
    function checkBoxChange(value:boolean,id:string){
        permitChange(value,id,memberItem.member_id)
    }
    return (
        <>
            <div className="channel_mgt_permit_item_card">
                <div className="channel_mgt_permit_card_header">
                    <div 
                        className="channel_mgt_permit_card_avatar"
                    >J</div>
                    <div
                        className="channel_mgt_permit_card_info"
                    >
                        <h4>
                            {memberItem.username} 
                            {memberItem.role=='admin'&&<span 
                                className="channel_mgt_permit_card_status admin">
                                管理员
                            </span>
                            }
                            {memberItem.role=='member'&&<span 
                                className="channel_mgt_permit_card_status member">
                                成员
                            </span>
                            }
                            {memberItem.role=='owner'&&<span 
                                className="channel_mgt_permit_card_status owner">
                                群主
                            </span>
                            }
                        </h4>
                    </div>
                </div>
                <div className="channel_mgt_permit_item_options">
                    <div className="channel_mgt_permit_item_item">
                        <span className="channel_mgt_permit_item_label">查看频道</span>
                        <label className="switch">
                            <MyCheckBox value={memberItem.can_view} onChange={checkBoxChange} id="can_view"></MyCheckBox>
                        </label>
                    </div>
                    <div className="channel_mgt_permit_item_item">
                        <span className="channel_mgt_permit_item_label">发送消息</span>
                        <label className="switch">
                            <MyCheckBox value={memberItem.can_send} onChange={checkBoxChange} id="can_send"></MyCheckBox>
                        </label>
                    </div>
                    <div className="channel_mgt_permit_item_item">
                        <span className="channel_mgt_permit_item_label">管理频道</span>
                        <label className="switch">
                            <MyCheckBox value={memberItem.can_manage} onChange={checkBoxChange} id="can_manage"></MyCheckBox>
                        </label>
                    </div>
                    <div className="channel_mgt_permit_item_item">
                        <span className="channel_mgt_permit_item_label">语音连接</span>
                        <label className="switch">
                            <MyCheckBox 
                                value={memberItem.can_connect}
                                disabled={memberItem.channelType == 'text'} onChange={checkBoxChange}
                                id="can_connect"
                            />
                        </label>
                    </div>
                    <div className="channel_mgt_permit_item_item">
                        <span className="channel_mgt_permit_item_label">静音成员</span>
                        <label className="switch">
                            <MyCheckBox 
                                value={memberItem.is_muted}
                                disabled={memberItem.channelType == 'text'} onChange={checkBoxChange}
                                id="is_muted"
                            />
                        </label>
                    </div>
                </div>
            </div>
        </>
    )
})


const ChannelItem = memo(({channelItem,onClick,disabled,role,reNewChannelList}:propsT)=>{
    const actChannelId = useAppSelector(state=>state.channel.actChannelId)
    const [messageApi, contextHolder] = message.useMessage();

    const [channelMgtVis,setChannelMgtVis] = useState(false)
    const [channelDelDlgVis,setChannelDelDlgVis] = useState(false)
    const [settingType,setSettingType] = useState<'channel'|'permission'|'notice'>('channel')
    
    const [defaultChannelSetting,setDefaultChannelSetting] = useState<ChannelSettingT>({ 
        channel_id:'',
        name:'',
        position:0,
        server_id:'',
        type:'',
        created_at:'',
        descripe:'',
        channel_count:0,
    })
    const [channelSetting,setChannelSetting] = useState<ChannelSettingT>({...defaultChannelSetting})
    const [memberList,setMemberList] = useState<memberT[]>([])

    const settingOptions = [
        {
            name:'频道设置',
            type:'channel',
            onClick:()=>{
                setSettingType('channel')
            }
        },
        {
            name:'权限设置',
            type:'permission',
            onClick:()=>{
                setSettingType('permission')
            }
        },
        // {
        //     name:'通知设置',
        //     type:'notice',
        //     onClick:()=>{
        //         setSettingType('notice')
        //     }
        // },
        {
            name:'删除频道',
            type:'delete',
            onClick:()=>{
                deleteChannelDlg()
            }
        }
    ]

    function handleClick(){
        !disabled&&onClick()
    }

    async function settingClick(e:React.MouseEvent<HTMLDivElement, MouseEvent>){
        e.stopPropagation()
        e.preventDefault()
        await getChannelInfo()
        await getChannelMembers()
    }

    function generateArray(length:number){
        return Array.from({length},(_,i)=>i)
    }

    function handleBaseChange(value:string|number,id:string){
        setChannelSetting(prev=>({...prev,[id]:value}))
    }

    function resetBaseChange(){
        console.log(defaultChannelSetting);
        if(!defaultChannelSetting.descripe) defaultChannelSetting.descripe = ''
        setChannelSetting(defaultChannelSetting)
    }

    function submitBaseChange(){
        http.post(api.server.editChannelInfo,{...channelSetting}).then(()=>{
            reNewChannelList()
        }).catch(err=>{
            messageApi.error(err.message)
        })
    }

    function deleteChannelDlg(){ 
        setChannelDelDlgVis(true)
    }

    function deleteChannel(id:string){
        http.post(api.server.deleteChannel,{channel_id:id}).then(()=>{
            reNewChannelList()
            setChannelDelDlgVis(false)
        }).catch(err=>{
            messageApi.error(err.message)
        })
    }

    async function getChannelMembers(){
        http.post(api.server.getChannelMembers,{channel_id:channelItem.channel_id}).then(res=>{
            const resData = res.data.map((item:memberT)=>{
                if(item.userType == 'guest'){
                    item.username = '游客' + item.user_id.substring(0,4)
                }
                return item
            })
            
            setMemberList(resData)
        }).catch(err=>{
            messageApi.error(err.message)
        })
    }

    async function getChannelInfo(){
        http.post(api.server.getChannelInfo,{channel_id:channelItem.channel_id}).then(res=>{
            const resData = res.data
            setDefaultChannelSetting(resData)
            setChannelSetting(resData)
            setChannelMgtVis(true)
        }).catch(err=>{
            messageApi.error(err.message)
        })
    }

    function onPermitChange(value:boolean,option:'can_view' | 'can_send' | 'can_manage' | 'can_connect' | 'is_muted',member_id:string){
        http.post(api.server.editMemberPermission,{channel_id:channelItem.channel_id,member_id,option,value}).then(()=>{
            setMemberList(prev=>{
                return prev.map(item=>{
                    if(item.member_id == member_id){
                        item[option] = value
                    }
                    return item
                })
            })
        }).catch(err=>{
            messageApi.error(err.message)
        })
    }
    
    return (
        <>
            {contextHolder}
            <div 
                className={
                    classNames(
                        'channel_chat_item',
                        {'channel_chat_item_act':channelItem.channel_id == actChannelId},
                        {
                            'channel_chat_disabled':disabled
                        }
                    )
                }
                onClick={()=>handleClick()}
            >
                {!disabled?
                    <span className="channel_chat_icon">
                        <svg width="16px" height="16px" viewBox="0 0 16 16">
                            <g stroke="none" strokeWidth="1" fill="none" fillRule="evenodd">
                                <g transform="translate(-218.000000, -99.000000)">
                                    <g transform="translate(218.000000, 99.000000)">
                                        <rect id="bg" fill="#037EF3" opacity="0" x="0" y="0" width="16" height="16">
                                        </rect>
                                        <path d="M10.75,2 C11.1296958,2 11.443491,2.28215388 11.4931534,2.64822944 L11.5,2.75 L11.5,4.5 L13.25,4.5 C13.6642136,4.5 14,4.83578644 14,5.25 C14,5.62969577 13.7178461,5.94349096 13.3517706,5.99315338 L13.25,6 L11.5,6 L11.5,10 L13.25,10 C13.6642136,10 14,10.3357864 14,10.75 C14,11.1296958 13.7178461,11.443491 13.3517706,11.4931534 L13.25,11.5 L11.5,11.5 L11.5,13.25 C11.5,13.6642136 11.1642136,14 10.75,14 C10.3703042,14 10.056509,13.7178461 10.0068466,13.3517706 L10,13.25 L10,11.5 L6,11.5 L6,13.25 C6,13.6642136 5.66421356,14 5.25,14 C4.87030423,14 4.55650904,13.7178461 4.50684662,13.3517706 L4.5,13.25 L4.5,11.5 L2.75,11.5 C2.33578644,11.5 2,11.1642136 2,10.75 C2,10.3703042 2.28215388,10.056509 2.64822944,10.0068466 L2.75,10 L4.5,10 L4.5,6 L2.75,6 C2.33578644,6 2,5.66421356 2,5.25 C2,4.87030423 2.28215388,4.55650904 2.64822944,4.50684662 L2.75,4.5 L4.5,4.5 L4.5,2.75 C4.5,2.33578644 4.83578644,2 5.25,2 C5.62969577,2 5.94349096,2.28215388 5.99315338,2.64822944 L6,2.75 L6,4.5 L10,4.5 L10,2.75 C10,2.33578644 10.3357864,2 10.75,2 Z M10,6 L6,6 L6,10 L10,10 L10,6 Z" id="形状" fill="currentColor" fillRule="nonzero">
                                        </path>
                                    </g>
                                </g>
                            </g>
                        </svg>
                    </span>:
                    <span className="channel_chat_icon">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" width="20" height="20" fill="currentColor">
                            <path d="M144 144v48H304V144c0-44.2-35.8-80-80-80s-80 35.8-80 80zM80 192V144C80 64.5 144.5 0 224 0s144 64.5 144 144v48h16c35.3 0 64 28.7 64 64V448c0 35.3-28.7 64-64 64H64c-35.3 0-64-28.7-64-64V256c0-35.3 28.7-64 64-64H80z"/>
                        </svg>
                    </span>
                }
                <div>{channelItem.name}</div>
                {role=='owner'&&<div className="channel_chat_item_delete" onClick={(e)=>settingClick(e)}>
                    <SettingOutlined  />
                </div>}
            </div>
            <MyDialog title="频道管理" visible={channelMgtVis} onClose={()=>setChannelMgtVis(false)}>
                <div className="channel_mgt">
                    <div className="channel_mgt_options">
                        {
                            settingOptions.map(item=>
                            <div 
                                key={item.name}
                                className={
                                    classNames(
                                        'channel_mgt_options_item',
                                        {
                                            'channel_mgt_options_item_act':settingType == item.type
                                        },
                                        {
                                            'channel_mgt_del':item.type == 'delete'
                                        }
                                    )
                                }
                                onClick={()=>item.onClick()}
                            >
                                {item.name}
                            </div>
                            )
                        }
                    </div>
                    <div className="channel_mgt_setting">
                        {settingType == 'channel'?
                        <div className="channel_mgt_setting_channel">
                            <div className="channel_mgt_setting_header">
                                <SettingFilled />
                                频道基本设置
                            </div>
                            <div className="channel_mgt_setting_channel_body">
                                <div className="channel_mgt_channel_item">
                                    <label htmlFor="name">频道名称</label>
                                    <MyInput 
                                        id="name" 
                                        value={channelSetting?.name}
                                        onChange={handleBaseChange}
                                    ></MyInput>
                                </div>
                                <div className="channel_mgt_channel_item">
                                    <label htmlFor="type">频道类型</label>
                                    {channelSetting?.type=='text'?
                                    <span className="type_label type_text">
                                        <i className="fas fa-comment-alt"></i> 
                                        文本频道
                                    </span>:
                                    <span className="type_label type_voice">
                                        <i className="fas fa-phone-alt"></i> 
                                        语音频道
                                    </span>
                                    }
                                </div>
                                <div className="channel_mgt_channel_item">
                                    <label htmlFor="position">位置排序</label>
                                    <select 
                                        title="排序位置" 
                                        id="position" 
                                        className="personal_form_control" 
                                        value={channelSetting?.position}
                                        onChange={(e)=>handleBaseChange(e.target.value, 'position')}
                                    >
                                        {generateArray(channelSetting?.channel_count).map(item=>
                                        <option key={item} value={item+1}>位置 {item + 1}</option>
                                        )}
                                    </select>
                                </div>
                                <div className="channel_mgt_channel_item">
                                    <label htmlFor="descripe">频道描述</label>
                                    <MyInput 
                                        type="textarea" 
                                        id='descripe'
                                        rows={2} 
                                        resize="none" 
                                        placeholder="该频道暂无描述"
                                        value={channelSetting.descripe}
                                        onChange={handleBaseChange}
                                    ></MyInput>
                                </div>
                                <div className="channel_mgt_channel_item_action">
                                    <MyButton type="guest" onClick={resetBaseChange}>重置</MyButton>
                                    <MyButton type="primary" onClick={submitBaseChange}>保存设置</MyButton>
                                </div>
                            </div>
                        </div>:
                        <div className="channel_mgt_setting_permit">
                            <div className="channel_mgt_setting_header">
                                <SettingFilled />
                                权限设置
                            </div>
                            <div className="channel_mgt_setting_permit_body">
                                <div 
                                    className="channel_mgt_permit_search"
                                >
                                    <span className="icon"><SearchOutlined /></span>
                                    <MyInput placeholder="搜索成员..."/>
                                </div>
                                <div className="channel_mgt_permit_members">
                                    {
                                    memberList.map(item=>
                                        <MemberPermissionCard 
                                                key={item.user_id}
                                                memberItem={item}
                                                permitChange={onPermitChange}
                                            />
                                        )
                                    }
                                </div>
                            </div>
                        </div>}
                    </div>
                </div>
            </MyDialog>
            <ConfirmDialog 
                visible={channelDelDlgVis} 
                onClose={()=>setChannelDelDlgVis(false)}
                onConfirm={()=>deleteChannel(channelItem.channel_id)}
                tipText="确定要删除此频道吗？"
            ></ConfirmDialog>
        </>
    )
})

export default ChannelItem